package com.punch.oauth.config;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.setting.profile.Profile;
import com.alibaba.fastjson.JSONObject;
import com.punch.common.constant.WXURLConstant;
import com.punch.common.exception.BusinessException;
import com.punch.common.simple.redis.utils.RedisUtil;
import com.punch.common.utils.SpringUtil;
import com.punch.oauth.exception.UaaExceptionEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;

@Component
@Slf4j
public class WXAccessTokenTask {


    @Value("${punch.wx.appid}")
    private String wxAppid;

    @Value("${punch.wx.secret}")
    private String wxSecret;

    @Resource
    private RestTemplate restTemplate;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SpringUtil springUtil;

    /**
     * 获取微信AccessToken,存放到redis中,微信AccessToken有效期是为7200秒
     */
    @Scheduled(fixedRate = 7000000)
    public void scheduledTask() {
        //测试环境/开发环境从生成环境中获取
        //从redis中获取
        if ("dev".equals(springUtil.getActiveProfile()) || "test".equals(springUtil.getActiveProfile())) {
            Map<String, String> uriVariables = CollUtil.newHashMap(1);
            ResponseEntity<JSONObject> exchange = restTemplate.getForEntity(WXURLConstant.PRODACCSSTOKEN, JSONObject.class, uriVariables);
            log.info("exchange:{}",exchange);
            StringBuilder sb = new StringBuilder();
            sb.append("wx:").append(wxAppid).append(":accessToken");
            redisUtil.setValue(sb.toString(), exchange.getBody().get("data"), 7000L);
        } else {
            Map<String, String> uriVariables = CollUtil.newHashMap(2);
            uriVariables.put("appid", wxAppid);
            uriVariables.put("secret", wxSecret);
            ResponseEntity<JSONObject> exchange = restTemplate.getForEntity(WXURLConstant.ACCSSTOKEN, JSONObject.class, uriVariables);
            //说明请求成功
            if (exchange.getBody().getInteger("errcode") == null) {
                String accessToken = exchange.getBody().getString("access_token");
                StringBuilder sb = new StringBuilder();
                sb.append("wx:").append(wxAppid).append(":accessToken");
                redisUtil.setValue(sb.toString(), accessToken, 7000L);
            } else {
                log.error("小程序获取accesstoken错误:{}", exchange.getBody());
                throw new BusinessException(UaaExceptionEnum.WX_ACCESS_TOKEN_ERROR);
            }
        }
    }

}
